from masoniteorm.relationships import has_one, belongs_to_many, has_many
from werkzeug.security import generate_password_hash, check_password_hash

from application.config import appSettings
from .base import BaseModel


class Node(BaseModel):
    __table__ = appSettings.db_prefix + 'nodes'


class User(BaseModel):
    __table__ = appSettings.db_prefix + 'users'

    __hidden__ = ['password_hash', 'deleted_at']

    @has_one('id', 'role_id')
    def role(self):
        return Role

    # 设置加密的方法,传入密码,对类属性进行操作
    def set_password_hash_attribute(self, value):
        return generate_password_hash(value, method='pbkdf2')

    @staticmethod
    def get_password_hash(password):
        return generate_password_hash(password, method='pbkdf2')

    # 设置验证密码的方法
    def check_password(self, user_pwd):
        return check_password_hash(self.password_hash, user_pwd)


class Role(BaseModel):
    __table__ = appSettings.db_prefix + 'roles'

    @belongs_to_many('role_id', 'menu_id', 'id', 'id', table='san_role_menus', pivot_id=None)
    def menus(self):
        return Menu

    @belongs_to_many('role_id', 'permission_id', 'id', 'id', table='san_role_permissions', pivot_id=None)
    def permissions(self):
        return Permission


class Permission(BaseModel):
    __table__ = appSettings.db_prefix + 'permissions'


class Menu(BaseModel):
    __table__ = appSettings.db_prefix + 'menus'

    @has_many('id', 'parent_id')
    def children(self):
        return Menu

    def format_type(self):
        if self.type == 1:
            return 'menu'
        if self.type == 2:
            return 'iframe'
        if self.type == 3:
            return 'link'
        return 'button'

    def format_menu(self, is_list=0):
        # children = self.children
        return {
            'id': self.id,
            'name': self.name,
            'parent_id': self.parent_id,
            'path': self.path,
            'component': self.component,
            'redirect': self.redirect,
            'order_num': self.order_num,
            'level': self.level,
            'meta': {
                'title': self.title,
                'icon': self.icon,
                'type': self.format_type() if is_list == 1 else self.type,
                'fullpage': self.fullpage,
                'hidden': self.hidden,
                'hidden_breadcrumb': self.hidden_breadcrumb,
                'affix': self.affix,
            },
            # 'children': [item.format_menu(is_list) for item in children if len(children) > 0],
        }


class MenuApi(BaseModel):
    __table__ = appSettings.db_prefix + 'menu_apis'


__all__ = [
    'Node',
    'User',
    'Role',
    'Permission',
    'Menu',
    'MenuApi',
]
